// ignore_for_file: depend_on_referenced_packages

import 'dart:convert';
import 'package:aitao_flutter/chat/model/message_attachment_model.dart';
import 'package:aitao_flutter/common_ui/circle_avatar.dart';
import 'package:aitao_flutter/style/box_style.dart';
import 'package:aitao_flutter/style/color_style.dart';
import 'package:aitao_flutter/style/radius_style.dart';
import 'package:aitao_flutter/utils/time_utils.dart';
import 'package:flutter/material.dart';
import 'package:nim_conversationkit/model/conversation_info.dart';
import 'package:nim_core/nim_core.dart';

class ConversationUserItem extends StatefulWidget {
  const ConversationUserItem({super.key, required this.info});
  final ConversationInfo info;
  @override
  State<ConversationUserItem> createState() => _ConversationUserItemState();
}

class _ConversationUserItemState extends State<ConversationUserItem> {
  int unCount = 0;
  @override
  Widget build(BuildContext context) {
    return Container(
      decoration: const BoxDecoration(
          border: Border(
              bottom: BorderSide(width: 1.0, color: ColorStyle.f8f8f8Color))),
      padding: const EdgeInsets.fromLTRB(0, 15, 0, 15),
      margin: const EdgeInsets.fromLTRB(15, 0, 15, 0),
      child: Row(children: [
        CircleAvatarWidget(url: widget.info.user?.avatar ?? '', gender: 4),
        Box.hBox10,
        Expanded(
            child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            Text(
              widget.info.user?.nick ?? '用户昵称',
              maxLines: 1,
              overflow: TextOverflow.ellipsis,
              style:
                  const TextStyle(fontSize: 15, color: ColorStyle.color333333),
            ),
            Box.vBox5,
            Text(
              setLastMessageContent(),
              maxLines: 1,
              overflow: TextOverflow.ellipsis,
              style:
                  const TextStyle(fontSize: 14, color: ColorStyle.color777777),
            ),
          ],
        )),
        Box.hBox20,
        // const Spacer(),
        Column(
          crossAxisAlignment: CrossAxisAlignment.end,
          children: [
            Text(
              TimeUtils.iMConversationshowTime(
                  (widget.info.session.lastMessageTime ?? 0) ~/ 1000, false),
              style:
                  const TextStyle(fontSize: 14, color: ColorStyle.color777777),
            ),
            Container(
              alignment: Alignment.center,
              width: 18,
              height: 18,
              decoration: BoxDecoration(
                  borderRadius: RadiusStyle.radiusAll(9),
                  color: unCount == 0
                      ? ColorStyle.whiteColor
                      : const Color(0xFFE94545)),
              child: const Text(
                '1',
                style: TextStyle(fontSize: 12, color: ColorStyle.whiteColor),
              ),
            )
          ],
        )
      ]),
    );
  }

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    getUnReadCount();
  }

  getUnReadCount() async {
    NIMSessionInfo i = NIMSessionInfo(
        sessionId: widget.info.session.sessionId,
        sessionType: NIMSessionType.p2p);
    NIMResult<NIMSession> result =
        await NimCore.instance.messageService.querySession(i);
    if (result.isSuccess) {
      setState(() {
        unCount = result.data?.unreadCount ?? 0;
      });
      debugPrint('获取成功:${result.data?.unreadCount ?? 0}');
    }
  }

  String setLastMessageContent() {
    debugPrint('extension:${widget.info.session.extension}');
    String txt = '';
    switch (widget.info.session.lastMessageType) {
      case NIMMessageType.custom:
        Map<String, dynamic> attachment =
            widget.info.session.lastMessageAttachment!.toMap();
        debugPrint('attachment:$attachment');
        String obj = json.encode(attachment);
        debugPrint('obj:$obj');
        Map deObj = json.decode(obj);
        debugPrint('deObj:$deObj');
        AttachmentCommonModel? m =
            AttachmentCommonModel.fromJson(deObj['data']);
        return m.title ?? '';
      case NIMMessageType.text:
        txt = widget.info.session.lastMessageContent ?? '文本消息';
      case NIMMessageType.audio:
        txt = '[语音]';
      case NIMMessageType.image:
        txt = '[图片]';
      case NIMMessageType.video:
        txt = '[视频]';
      case NIMMessageType.location:
        txt = '[位置]';
      case NIMMessageType.notification:
        txt = '[通知类型]';
      case NIMMessageType.file:
        txt = '[文件类型]';
      case NIMMessageType.tip:
        txt = widget.info.session.lastMessageContent ?? '提醒消息';
      case NIMMessageType.robot:
        txt = '[机器人消息]';
      default:
        txt = '[未知消息]';
    }
    return txt;
  }
}
